<template>
  <lay-container
    :fluid="true"
    style="padding: 10px"
  >
    <lay-row space="10">
      <lay-col
        md="5"
        v-show="btnIcon"
      >
        <lay-card>
          <lay-input
            placeholder="搜索部门"
            size="xs"
            v-model="searchdepartmentName"
            :allow-clear="true"
            @blur="getGetDepartmentInfo"
            @clear="getGetDepartmentInfo"
          ></lay-input>
          <lay-row
            space="10"
            class="header_left"
          >
            <lay-col md="12">
              <div
                v-for="(item, index) in GetDepartmentInfoList"
                :key="index"
                @click="bgcIndex = index"
              >

                <lay-tooltip :is-dark="false">
                  <template #content>
                    <lay-button
                      border="green"
                      size="sm"
                      @click="editBumen(item)"
                    >编辑 </lay-button>
                    <lay-button
                      border="red"
                      size="sm"
                      @click="dleBumen(item)"
                    >删除 </lay-button>
                  </template>
                  <lay-tag
                    class="mtop"
                    :color="index === bgcIndex ? '#165DFF' : ''"
                  >
                    {{item.departmentName}}
                  </lay-tag>
                </lay-tooltip>
              </div>
            </lay-col>
            <lay-col
              md="6"
              mdOffset="6"
            >
              <lay-button
                size="sm"
                type="primary"
                @click=" addBumen "
                v-if="httpUrls.includes('/Setting/AddorUpdateDepartmentInfo')"
              >添加部门</lay-button>
            </lay-col>
          </lay-row>
        </lay-card>
      </lay-col>
      <lay-col :md="btnIcon ? 19 : 24">
        <lay-card>
          <span @click="btnIcon = !btnIcon">
            <i
              class="layui-icon layui-icon-shrink-right"
              v-if="btnIcon"
            ></i>
            <i
              class="layui-icon layui-icon-spread-left"
              v-else
            ></i>
          </span>
          <div class="header">
            <div class="cearch_box">
              <!-- <lay-input
                v-model="time"
                size="sm"
                placeholder="搜索人员"
              ></lay-input>
              <lay-button
                @click="submitClick"
                class="btn"
                type="primary"
                size="xs"
              >查询
              </lay-button>
              <lay-button
                @click="submitClick"
                type="primary"
                size="xs"
              >重置
              </lay-button> -->
            </div>
            <div>
              <lay-button
                type="primary"
                @click="addUser"
                size="sm"
                v-if="httpUrls.includes('/Setting/InsertorUpdateUser')"
              >
                <lay-icon type="layui-icon-add-circle"></lay-icon>
                添加
              </lay-button>
            </div>
          </div>

          <lay-table
            v-model:selectedKeys="selectedKeys"
            id="id"
            :columns="columns"
            :dataSource="dataSource"
            :checkbox="checkbox"
            :default-toolbar="false"
          >
            <template #sex="{data}">
              <span>{{ data.sex == 1 ? '男' : '女'}}</span>
            </template>
            <template #alter="{data}">
              <lay-button
                type="primary"
                size="sm"
                v-if="httpUrls.includes('/Setting/InsertorUpdateUser')"
                @click="editUser(data)"
              >编辑</lay-button>

              <!-- <lay-button
                size="sm"
                type="warm"
                v-if="httpUrls.includes('/Setting/InsertorUpdateUser')"
                @click="alterPwd(data)"
              >修改密码</lay-button> -->

              <lay-button
                type="danger"
                size="sm"
                v-if="httpUrls.includes('/Setting/DeleteUser')"
                @click="dleUser(data)"
              >删除</lay-button>
            </template>
          </lay-table>

          <lay-page
            v-model="current"
            v-model:limit="limit"
            :pages="pages"
            :total="total"
            :show-count="true"
            :show-limit="true"
            :showSkip="true"
            :show-page="true"
            @change="changePage"
          ></lay-page>
        </lay-card>
      </lay-col>
    </lay-row>

    <lay-layer
      type="drawer"
      v-model="visible"
      :title="title"
      :btn="addUSerBtn"
    >
      <lay-form
        :model="validateModel"
        ref="layFormRef"
        required
      >
        <lay-form-item
          label="姓名"
          prop="username"
        >
          <lay-input v-model="validateModel.username"></lay-input>
        </lay-form-item>
        <lay-form-item
          label="密码"
          prop="password"
        >
          <lay-input
            v-model="validateModel.password"
            type="password"
            :password="true"
          ></lay-input>
        </lay-form-item>

        <lay-form-item
          label="手机号"
          prop="phone"
        >
          <lay-input v-model="validateModel.phone"></lay-input>
        </lay-form-item>

        <lay-form-item
          label="部门"
          prop="departmentId"
          class="bumen"
        >
          <lay-select
            v-model="validateModel.departmentId"
            :show-search="true"
            :allow-clear="true"
          >
            <lay-select-option
              v-for="(item, index) in GetDepartmentInfoList"
              :key="index"
              :label="item.departmentName"
              :value="item.departmentId"
            ></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item
          label="角色"
          class="bumen"
        >
          <lay-select
            v-model="validateModel.roleId"
            :show-search="true"
            :allow-clear="true"
          >
            <lay-select-option
              v-for="(item, index) in rolesList"
              :key="index"
              :label="item.roleName"
              :value="item.roleId"
            ></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item label="岗位">
          <lay-input v-model="validateModel.station"></lay-input>
        </lay-form-item>

        <lay-form-item label="性别">
          <lay-radio
            v-model="validateModel.sex"
            name="specialty"
            value="1"
          >男</lay-radio>
          <lay-radio
            v-model="validateModel.sex"
            name="specialty"
            value="2"
          >女</lay-radio>
        </lay-form-item>
        <lay-form-item label="职称">
          <lay-input v-model="validateModel.title"></lay-input>
        </lay-form-item>
        <lay-form-item label="证书编号">
          <lay-input v-model="validateModel.certificateNo"></lay-input>
        </lay-form-item>

        <lay-form-item label="学历">
          <lay-input v-model="validateModel.education"></lay-input>
        </lay-form-item>
      </lay-form>
    </lay-layer>

    <lay-layer
      :title="titles"
      v-model="addVisible"
      :btn="btn"
      area="300px"
      :offset="['200px','200px']"
    >

      <div class="add_del">
        <lay-input
          placeholder="请输入部门"
          v-model="departmentName"
        ></lay-input>
      </div>
    </lay-layer>

    <lay-layer
      title="提示"
      v-model="delVisible"
      :btn="delBumrnAlter"
      area="300px"
      :offset="['200px','200px']"
    >

      <div class="add_del">
        确定删除该部门？
      </div>
    </lay-layer>

    <lay-layer
      title="提示"
      v-model="userVisible"
      :btn="delUserAlter"
      area="300px"
    >
      <div class="add_del">
        确定删除该用户？
      </div>
    </lay-layer>


    <lay-layer
      :title="'修改密码' + ' —— ' + pwdFrom.username"
      v-model="pwdVisible"
      :btn="pwdBtn"
      area="300px"
    >
      <div class="add_del">
        <lay-input placeholder="请输入密码" v-model="pwdFrom.password"></lay-input>
      </div>
    </lay-layer>
  </lay-container>
</template>
<script lang="ts" >
import { defineComponent, ref, onMounted, reactive, toRefs } from "vue";
import { layer } from "@layui/layer-vue";
// import { PostFrom } from "../../../api/request";
import {
  GetUsers,
  DelDepartmentInfo,
  AddorUpdateDepartmentInfo,
  GetDepartmentInfo,
  InsertorUpdateUser,
  DeleteUser,
  GetRoleInfos,
} from "../../../api/module/user";
export default defineComponent({
  setup() {
    let httpUrl: any = [];
    httpUrl = sessionStorage.getItem("httpUrl");
    httpUrl = JSON.parse(httpUrl);

    const data = reactive({
      httpUrls: httpUrl,
      selectedKeys: "",
      pwdVisible: false,
      pwdFrom: {
        password: '',
      } as any,
      typeBm: "add",
      typeUser: "add",
      departmentName: "",
      searchdepartmentName: "",
      titles: "添加部门",
      title: "新增用户",
      checkbox: true,
      visible: false,
      btnIcon: true,
      addVisible: false,
      delVisible: false,
      userVisible: false,
      time: "",
      tabItem: "1",
      bgcIndex: 0,
      current: 1,
      total: 0,
      pages: 0,
      limit: 10,
      GetDepartmentInfoList: [] as any,
      delObj: {} as any,
      editBumenId: 0,
      validateModel: {
        userid: 0,
        roleId: 0,
        // createtime: "2022-12-12",
        // logintime: "2022-12-30",
      } as any,
      columns: [
        {
          title: "序号",
          width: "60px",
          type: "number",
          fixed: "left",
        },
        {
          title: "姓名",
          key: "username",
          ellipsisTooltip: true,
        },
        {
          title: "性别",
          customSlot: "sex",
        },
        {
          title: "学历",
          key: "education",
          ellipsisTooltip: true,
        },
        {
          title: "职称",
          key: "title",
          ellipsisTooltip: true,
        },
        {
          title: "证书编号",
          key: "department",
          ellipsisTooltip: true,
        },
        {
          title: "部门",
          key: "departmentName",
          ellipsisTooltip: true,
        },
        {
          title: "岗位",
          key: "station",
          ellipsisTooltip: true,
        },
        {
          title: "手机号",
          key: "phone",
          ellipsisTooltip: true,
        },
        {
          title: "操作",
          width: "200px",
          customSlot: "alter",
        },
      ],
      dataSource: [] as any,
      rolesList: [] as any,
    });

    onMounted(() => {
      if (data.httpUrls.includes("/Setting/GetDepartmentInfo")) {
        getGetDepartmentInfo();
      }

      if (data.httpUrls.includes("/Setting/GetUsers")) {
        getUser();
      }

      if (data.httpUrls.includes("/Setting/GetRoleInfos")) {
        getRoleList();
      }
    });

    const getRoleList = async () => {
      const res: any = await GetRoleInfos({
        pageIndex: 1,
        pagePerCount: 500,
        condition: "",
      });
      if (res.code == 200) {
        data.rolesList = res.data.datas;
      }
    };

    const addBumen = () => {
      data.editBumenId = 0;
      data.departmentName = "";

      data.typeBm = "add";
      data.titles = "添加部门";
      data.addVisible = true;
    };

    const editBumen = (item: any) => {
      data.typeBm = "edit";
      data.titles = "编辑部门";
      data.departmentName = item.departmentName;
      data.editBumenId = item.departmentId;
      data.addVisible = true;
    };

    const dleBumen = (item: any) => {
      data.delVisible = true;
      data.editBumenId = item.departmentId;
    };

    const delBumrnAlter = [
      {
        text: "确认",
        callback: async () => {
          const res: any = await DelDepartmentInfo({
            id: data.editBumenId,
          });
          if (res.code === 200) {
            data.delVisible = false;
            getGetDepartmentInfo();
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.delVisible = false;
        },
      },
    ];

    const delUserAlter = [
      {
        text: "确认",
        callback: async () => {
          const res: any = await DeleteUser({
            userid: data.editBumenId,
          });
          if (res.code === 200) {
            data.editBumenId = 0;
            data.userVisible = false;
            getUser();
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          data.userVisible = false;
        },
      },
    ];

    const getGetDepartmentInfo = async () => {
      const res: any = await GetDepartmentInfo({
        pageIndex: 1,
        pagePerCount: 100,
        condition: data.searchdepartmentName,
      });
      if (res.code === 200) {
        data.GetDepartmentInfoList = res.data.datas;
      }
    };

    const btn = [
      {
        text: "确认",
        callback: () => {
          addBm();
          data.addVisible = false;
        },
      },
      {
        text: "取消",
        callback: () => {
          data.addVisible = false;
        },
      },
    ];

    const editUser = (item: any) => {
      data.visible = true;
      data.typeUser = "edit";
      data.title = "编辑用户";
      data.validateModel = { ...item };
    };

    const addBm = async () => {
      const res: any = await AddorUpdateDepartmentInfo({
        departmentName: data.departmentName,
        departmentId: data.editBumenId ? data.editBumenId : 0,
      });
      if (res.code === 200) {
        getGetDepartmentInfo();
      }
    };

    const pwdBtn = [
      {
        text: "确认",
        callback: async () => {
          const res: any = await InsertorUpdateUser({
            ...data.pwdFrom,
          });
          if (res.code == 200) {
            data.pwdVisible = false;
          }
        },
      },
      {
        text: "取消",
        callback: () => {
          // alert("取消事件");
          data.pwdVisible = false;
        },
      },
    ];

    const getUser = async () => {
      let obj = {
        pageIndex: data.current,
        pagePerCount: data.limit,
        condition: {},
      };
      const res: any = await GetUsers(obj);
      if (res.code === 200) {
        data.total = res.data.totalCount;
        // data.pages = res.data.pageCount;
        data.dataSource = res.data.datas;
      }
    };

    const submitClick = () => {};

    const changePage = (item: any) => {
      data.limit = item.limit;
      data.current = item.current;
      getUser();
    };

    const addUser = () => {
      Object.keys(data.validateModel).forEach((key: any) => {
        data.validateModel[key] = "";
      });
      data.validateModel.userid = 0;
      data.validateModel.logintime = "2022-12-30";
      data.validateModel.createtime = "2022-12-30";
      data.validateModel.roleId = [];
      data.visible = true;
      data.title = "新增用户";
      data.typeUser = "add";
    };

    const submit = async () => {
      let roleId: any = "";
      let obj = {
        ...data.validateModel,
      };
      // if (obj.roleId && obj.roleId.length) {
      //   roleId = obj.roleId.join(",");
      //   delete obj.roleId;
      // }
      const res: any = await InsertorUpdateUser({
        ...obj,
        // roleId: roleId,
      });
      if (res.code === 200) {
        data.visible = false;
        getUser();
      }
      // PostFrom("InsertorUpdateUser", data.validateModel).then((res: any) => {
      //   console.log("ewsssss", res);
      //   if (res.code == 200) {
      //     getUser();
      //     data.visible = false;
      //   }
      // });
    };

    // 清除校验
    const clearValidate = () => {
      layFormRef.value.clearValidate();
    };

    const editItem = (item: any) => {
      data.visible = true;
      data.title = "编辑用户";
    };

    let id = null;
    const dleUser = (item: any) => {
      data.editBumenId = item.userid;
      data.userVisible = true;
    };

    const layFormRef: any = ref();
    const addUSerBtn = [
      {
        text: "确认",
        callback: async () => {
          layFormRef.value.validate(
            (isValidate: any, model: any, errors: any) => {
              if (isValidate) {
                submit();
              } else {
              }
            }
          );
        },
      },
      {
        text: "取消",
        callback: () => {
          // alert("取消事件");
          data.visible = false;
        },
      },
    ];

    const alterPwd = (item: any) => {
      for (const key in data.pwdFrom) {
        data.pwdFrom[key] = '';
      }
      data.pwdFrom = {...item};

      data.pwdVisible = true;
    }

    return {
      btn,
      addUSerBtn,
      ...toRefs(data),
      layFormRef,
      submitClick,
      changePage,
      addUser,
      clearValidate,
      editItem,
      addBumen,
      editBumen,
      dleBumen,
      delBumrnAlter,
      delUserAlter,
      pwdBtn,
      alterPwd,
      editUser,
      getGetDepartmentInfo,
      dleUser,
    };
  },
});
</script>

<style>
.bumen .layui-select {
  width: 100% !important;
}
</style>

<style lang="less" scoped>
.add_del {
  margin: 10px 20px;
}
.header_left {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eeeeee;
  margin: 12px 0;
  padding-top: 8px;

  div {
    cursor: pointer;
  }

  .left_jurisdiction {
    width: 100%;
  }
}

.mtop {
  margin-bottom: 10px;
}
.cearch_box {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .w {
    width: 50%;
  }

  .btn {
    margin: 0 16px;
  }
}

.layui-form {
  margin-top: 26px;
  margin-right: 26px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
</style>
